package com.spark.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring工具类 方便在非spring管理环境中获取bean
 *
 * @author LYCHEE
 * @date 2025/2/14 14:38
 *
 */
@Component
public class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware {

    /**
     * Spring应用上下文环境
     */
    private static ConfigurableListableBeanFactory beanFactory;

    private static ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        // 初始化beanFactory静态变量
        SpringUtils.beanFactory = configurableListableBeanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 初始化applicationContext静态变量
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * 获取SpringBean实例
     * @param name bena实例名称
     * @return 一个以所给名字注册的bean的实例
     * @param <T> 类型
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name){
        return (T) beanFactory.getBean(name);
    }

    /**
     * 获取SpringBean实例
     * @param clazz bena实例class对象
     * @return 一个以所给class注册的bean的实例
     * @param <T> 类型
     */
    public static <T> T getBean(Class<T> clazz) {
        return beanFactory.getBean(clazz);
    }

}
